<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id?"编辑企业":"新增企业" }}</span>
      </div>

    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :rules="addRules" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="name">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              <el-upload
                class="upload-demo"
                action="#"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :http-request="handlePreview"
              >
                <img v-if="id" :src="addForm.businessLicenseUrl" style="width: 100px; height: 100px;display: block;margin-bottom: 10px" alt="">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2MB</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="submitForm">{{ id?"编辑":"添加" }}</el-button>
      </div>
    </footer>

  </div>
</template>

<script>
import { getIndustryAPI, uploadAPI, addEnterpriseAPI, getEnterpriseInfoAPI, editEnterpriseAPI } from '@/api/enterprise'

export default {

  data() {
    return {
      // 表单数据
      addForm: {
        name: '', // 企业名称
        businessLicenseName: '', // 营业执照名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '', // 营业执照id
        id: '' // 企业id
      },
      // 表单验证规则
      addRules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请选择所在行业', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            const reg = /^(?:(?:\+|00)86)?1\d{10}$/
            if (reg.test(value)) {
              callback()
            } else {
              callback(new Error('联系电话格式不正确'))
            }
          } }
        ],
        businessLicenseUrl: [
          { required: true, message: '请上传营业执照', trigger: 'change' }
        ]
      },
      // 行业列表
      industryList: []
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    // 渲染时获取行业列表
    this.getIndustry()
    // 渲染时查看编辑企业信息,有id时调用接口
    if (this.id) {
      this.getEnterpriseInfo()
    }
  },
  methods: {
    // 获取行业列表
    async  getIndustry() {
      const res = await getIndustryAPI()
      this.industryList = res.data
    },
    // 上传图片,成功后把图片信息保存到表单中
    async  handlePreview(data) {
      const fd = new FormData()
      fd.append('file', data.file)
      fd.append('type', 'businessLicense')
      const res = await uploadAPI(fd)
      this.addForm.businessLicenseUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id
    },
    // 上传,成功后回显
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 上传前校验,限制上传格式和大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 确定提交
    submitForm() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 调用添加企业接口,有id时调用编辑企业接口
          if (this.id) {
            await this.editEnterprise()
            this.$message.success('编辑成功')
          } else {
            await this.addEnterprise()
            this.$message.success('添加成功')
          }

          // 提示

          // 重置表单
          this.$refs.ruleForm.resetFields()
          this.$router.back()
        } else {
          this.$message.error('请完善表单')
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    // 查看编辑企业信息
    async getEnterpriseInfo() {
      const res = await getEnterpriseInfoAPI(this.id)
      this.addForm = res.data
    },

    // 添加企业信息提交确认
    async addEnterprise() {
      const { name, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber } = this.addForm
      await addEnterpriseAPI({ name, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber })
    },
    // 编辑企业信息提交确认
    async editEnterprise() {
      const { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber } = this.addForm
      await editEnterpriseAPI({ name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber })
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
